﻿using System;
using System.Collections;
using UnityEngine;
using Object = UnityEngine.Object;

/// <summary>
/// 资源加载管理器
/// </summary>
[HelpURL("https://www.bilibili.com/video/av66427088?p=9")]
public class ResourcesManager : Singleton<ResourcesManager>
{
    /// <summary>
    /// 同步加载资源, 如果是物体, 就直接实例化并返回
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="name"></param>
    /// <returns></returns>
    public T Load<T>(string name) where T : Object
    {
        T res = Resources.Load<T>(name);
        if (res is GameObject)
        {
            return GameObject.Instantiate(res);
        }

        return res;
    }

    /// <summary>
    /// 异步加载, 如果是物体, 就直接实例化 并调用回调
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="name"></param>
    /// <param name="callback"></param>
    public void LoadAsync<T>(string name, Action<T> callback) where T : Object
    {
        MonoCoroutine.Instance.StartCoroutine(ReallyLoadAsync(name, callback));
    }

    private IEnumerator ReallyLoadAsync<T>(string name, Action<T> callback) where T : Object
    {
        ResourceRequest rr = Resources.LoadAsync<T>(name);
        yield return rr;

        T res;
        if (rr.asset is GameObject)
        {
            res = GameObject.Instantiate(rr.asset) as T;
        }
        else
        {
            res = rr.asset as T;
        }

        if (rr == null)
            throw new NullReferenceException($"No such name '{name}' resource!!");

        callback(res);

    }
}
